<?php


defined("IN_TS") or die("Access Denied.");

$userid		= $TS_USER['user']['userid'];
$username	= $TS_USER['user']['username'];
$title = "我要分享";

switch($ts) {
	case "":
		$method = isset($_SERVER["REQUEST_METHOD"]) ? strtoupper($_SERVER["REQUEST_METHOD"]) :"GET";
		if("GET" == $method) {
			$arrCate = $new['tbshare']->findAll('tbshare_cates',null,"paixu DESC");
			include template("share");
		} elseif("POST" == $method) {
			$shareurl = trim($_POST["shareurl"]);
			$tburl	  = @parse_url($shareurl);
			$cateid	  = intval($_POST["cateid"]);
			$notice   = $new['tbshare']->__('url_invalid');
			if(is_array($tburl) && !empty($tburl['query'])) {
				$query = array();
				@parse_str($tburl['query'],$query);
				if(is_array($query) && !empty($query['id'])) {
					$tmp = $new['tbshare']->getTbItem($query['id']);
					if(property_exists($tmp,"item_get_response")) {
						//淘宝商品入库
						$item = $tmp->item_get_response->item;
						//处理图片
						
						$arrData = array(
							'city'		=>$item->location->city,
							'state'		=>$item->location->state,
							'nick'		=>$item->nick,
							'num_iid'	=>$item->num_iid,
							'pic_url'	=>$item->pic_url,
							'price'		=>intval(floatval($item->price) * 100),
							'title'		=>$item->title,
							'cateid'	=>$cateid,
							'userid'	=>$userid,
							'username'	=>$username,
							'shareurl'	=>$shareurl,
							'addtime'	=> time()
						);
						$tbshareid = $db->insertArr($arrData,dbprefix.'tbshare');
						
						$img = tsGetImg($item->pic_url,$tbshareid,'tbshare',array("jpg","png","gif"));
						$new['tbshare']->update("tbshare","tbshareid='$tbshareid'",array("pic"=>$img['url']));

						//更新商品数量
						$db->query("UPDATE ".dbprefix."tbshare_cates SET num=num+1 WHERE cateid='$cateid'");
						//更新用户分享数目
						if($db->once_fetch_assoc("SELECT userid FROM ".dbprefix."tbshare_user WHERE userid='$userid' LIMIT 1")) {
							$db->query("UPDATE ".dbprefix."tbshare_user SET sharecount=sharecount+1 WHERE userid='$userid'");
						} else {
							$db->insertArr(array("userid"=>$userid,"username"=>$username,"sharecount"=>1),dbprefix.'tbshare_user');
						}
						header("Location: ".SITE_URL.tsUrl('tbshare','show',array('id'=>$tbshareid)));
					} else {
						tsNotice($new['tbshare']->__('error_to_redo'));
					}
				} else {
					tsNotice($notice);
				}
			} else {
				tsNotice($notice);
			}
		}
		break;
}

